import * as vscode from "vscode"
import { Controller } from "@core/controller"
import { ClineAPI } from "./cline"
import { getGlobalState } from "@core/storage/state"

export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarController: Controller): ClineAPI {
	const api: ClineAPI = {
		setCustomInstructions: async (value: string) => {
			await sidebarController.updateCustomInstructions(value)
			outputChannel.appendLine("Custom instructions set")
		},

		getCustomInstructions: async () => {
			return (await getGlobalState(sidebarController.context, "customInstructions")) as string | undefined
		},

		startNewTask: async (task?: string, images?: string[]) => {
			outputChannel.appendLine("Starting new task")
			await sidebarController.clearTask()
			await sidebarController.postStateToWebview()
			await sidebarController.postMessageToWebview({
				type: "action",
				action: "chatButtonClicked",
			})
			await sidebarController.postMessageToWebview({
				type: "invoke",
				invoke: "sendMessage",
				text: task,
				images: images,
			})
			outputChannel.appendLine(
				`Task started with message: ${task ? `"${task}"` : "undefined"} and ${images?.length || 0} image(s)`,
			)
		},

		sendMessage: async (message?: string, images?: string[]) => {
			outputChannel.appendLine(
				`Sending message: ${message ? `"${message}"` : "undefined"} with ${images?.length || 0} image(s)`,
			)
			await sidebarController.postMessageToWebview({
				type: "invoke",
				invoke: "sendMessage",
				text: message,
				images: images,
			})
		},

		pressPrimaryButton: async () => {
			outputChannel.appendLine("Pressing primary button")
			await sidebarController.postMessageToWebview({
				type: "invoke",
				invoke: "primaryButtonClick",
			})
		},

		pressSecondaryButton: async () => {
			outputChannel.appendLine("Pressing secondary button")
			await sidebarController.postMessageToWebview({
				type: "invoke",
				invoke: "secondaryButtonClick",
			})
		},

		getLastAssistantMessage: async () => {
			outputChannel.appendLine("Getting last assistant message")
			
			// 获取当前任务
			if (!sidebarController.task) {
				return "没有活动的任务"
			}
			
			// 获取所有消息
			const messages = sidebarController.task.clineMessages
			if (!messages || messages.length === 0) {
				return "没有消息"
			}
			
			// 首先尝试查找最新的工具调用结果消息（type为"say"且say为"tool"的消息）
			// 这些消息包含了实际生成的代码
			const toolMessages = messages.filter(m => 
				m.type === "say" && m.say === "tool" && 
				(m.text?.includes("newFileCreated") || m.text?.includes("editedExistingFile"))
			)
			
			if (toolMessages.length > 0) {
				// 获取最新的工具调用结果消息
				const lastToolMessage = toolMessages[toolMessages.length - 1]
				
				try {
					// 尝试解析工具调用结果
					const toolData = JSON.parse(lastToolMessage.text || "{}")
					if (toolData.content) {
						return `文件路径: ${toolData.path || "未知"}\n\n${toolData.content}`
					}
				} catch (e) {
					// 如果解析失败，返回原始消息
					return lastToolMessage.text || "工具调用结果没有内容"
				}
			}
			
			// 如果没有找到工具调用结果消息，则查找最新的助手消息
			const assistantMessages = messages.filter(m => 
				m.type === "say" && (m.say === "text" || m.say === "completion_result")
			)
			
			if (assistantMessages.length === 0) {
				return "没有助手消息"
			}
			
			// 获取最新的助手消息
			const lastAssistantMessage = assistantMessages[assistantMessages.length - 1]
			
			// 返回消息内容
			return lastAssistantMessage.text || "助手消息没有内容"
		},

		getAllMessages: async () => {
			outputChannel.appendLine("Getting all messages")
			
			// 获取当前任务
			if (!sidebarController.task) {
				return JSON.stringify({ error: "没有活动的任务" })
			}
			
			// 获取所有消息
			const messages = sidebarController.task.clineMessages
			if (!messages || messages.length === 0) {
				return JSON.stringify({ error: "没有消息" })
			}
			
			// 创建消息摘要
			const messageSummary = messages.map(m => {
				const summary = {
					ts: m.ts,
					time: new Date(m.ts).toISOString(),
					type: m.type,
					subType: m.type === "ask" ? m.ask : m.say,
					hasText: !!m.text,
					textLength: m.text ? m.text.length : 0,
					hasImages: m.images && m.images.length > 0,
					imageCount: m.images ? m.images.length : 0
				}
				
				// 如果是工具消息，尝试解析工具类型
				if (m.type === "say" && m.say === "tool" && m.text) {
					try {
						const toolData = JSON.parse(m.text)
						if (toolData.tool) {
							Object.assign(summary, { 
								toolType: toolData.tool,
								path: toolData.path,
								hasContent: !!toolData.content,
								contentLength: toolData.content ? toolData.content.length : 0
							})
						}
					} catch (e) {
						// 解析失败，忽略
					}
				}
				
				return summary
			})
			
			// 返回消息数组和摘要
			return JSON.stringify({
				count: messages.length,
				summary: messageSummary,
				messages: messages
			}, null, 2)
		},
	}

	return api
}
